
package com.jic.interaction.weChatCardAndOffers.common.utils;

import com.jic.interaction.hereWeGo.common.utlis.HereWeGoHttpUtil;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * @author evan_qb
 * @date 2018/8/13 14:54
 * HttpClient工具
 */
public class WeChatCardAndOffersHttpUtil {
    private static final Log log = LogFactory.getLog(HereWeGoHttpUtil.class.getName());

    /**
     * POST请求
     *
     * @param url
     * @param jsonStr
     * @return
     */
    public static String sendpostJson(String url, String jsonStr) throws Exception, IOException, ExecutionException, InterruptedException {
        log.info("传入参数: " + url);
        String result = null;
        AsyncHttpClient httpClient = new AsyncHttpClient();
        AsyncHttpClient.BoundRequestBuilder builder = httpClient.preparePost(url);
        CloseableHttpResponse response = null;
        builder.setBodyEncoding("UTF-8");
        Future<Response> f = builder.execute();
        String body = (f.get()).getResponseBody("UTF-8");
        log.info("返回参数: " + body);
        return body;
    }

    /**
     * GET请求
     *
     * @param url
     * @return
     */
    public static String sendGet(String url, Map<String, String> map) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpGet get = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            //创建uri
            URIBuilder builder = new URIBuilder(url);
            if (map != null) {
                for (String key : map.keySet()) {
                    builder.addParameter(key, map.get(key));
                }
            }
            URI uri = builder.build();
            //创建get请求
            HttpGet httpGet = new HttpGet(uri);
            //执行请求
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                result = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (Exception e) {
        } finally {
            try {
                httpClient.close();
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return result;
    }
}